package com.ncmmall.mall.controller.fs;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

/**
 * 图片下载
 *
 * @author likaikai
 */
@Controller
@RequestMapping(value = "/image")
public class ImageDownloadController {

    private Logger logger = LoggerFactory.getLogger(ImageDownloadController.class);

    /**
     * 下载
     *
     * @param requestWith
     * @param request
     * @return
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    private void download(String url, HttpServletResponse response) {
        if (StringUtils.isBlank(url)) {
            return;
        }
        try (OutputStream os = response.getOutputStream()) {
            InputStream is = new URL(url).openStream();
            response.setHeader("Content-disposition", "attachment; filename=" + System.currentTimeMillis() + ".jpg");
            IOUtils.copyLarge(is, os);
        } catch (Exception e) {
            logger.error("[图片下载错误]", e);
        }
    }
}
